# Overview

MicroEJ Library: `app-verifier`.

This library verifies **signed application binaries** (for example a signed `.fo.signed` application) and gives
access to their content once the certificate chain and the signature have been validated.

A signed application is a DER-encoded stream wrapping a version, a signature algorithm identifier, an X.509
certificate chain, the application content, and a digital signature over that content:

```text
SEQUENCE  SignedApplication
├─ INTEGER      version
├─ SEQUENCE     signatureAlgorithm   { OID, NULL }
├─ SEQUENCE     certificateChain     [ X.509 cert, ..., signer's cert ]   ← signer = last certificate
├─ [commandId]  command              ← tag carries the command id
│                  └─ content        ← metadata + application binary (.fo); bytes covered by the signature
└─ BIT STRING   signature
```

When verifying, the verifier:

1. validates the **certificate chain** against trusted certificate authorities and checks that the signer
   is **authorized**, then
2. exposes the application content as an `InputStream`.

The **digital signature** (`SHA256withRSA` or `SHA256withECDSA`) is verified _lazily_: it is checked only
once the application binary stream has been entirely consumed. The content is therefore streamed _before_ the
signature is confirmed, and the outcome is reported by `SignedApplicationBinaryInputStream.isVerified()` once
the stream has been fully consumed.

```mermaid
sequenceDiagram
    participant C as Caller
    participant V as SignedApplicationVerifier
    participant App as SignedApplicationBinaryInputStream

    C->>V: verify(signedApplication)
    V->>V: read version & signature algorithm
    V->>V: validate certificate chain + authorization
    V-->>C: SignedApplicationBinaryInputStream
    loop read binary payload
        C->>App: read()
        Note over V,App: signature updated with each byte,<br/>not yet verified
    end
    C->>App: read() reaches end of stream
    App->>App: verify signature (BIT STRING)
    C->>App: isVerified()
    alt signature invalid
        App-->>C: InvalidSignatureException
    else signature valid
        App-->>C: true
    end
```

Certificate-chain validation is pluggable through the `CertificateChainValidator` interface:

- `DefaultCertificateChainValidator` validates the chain against a set of trusted CAs. The chain root is
  trusted when it has been signed by one of those CAs, or when it is byte-identical to one of them (so a
  self-signed certificate is trusted only if it is itself one of the trusted CAs). The trusted CAs are
  provided at construction time, either directly through `new DefaultCertificateChainValidator(trustedCAs)`
  (for example loaded from a `KeyStore` or a secure storage) or, with the `fromResource()` factory, from the
  Application resource file identified by the `appverifier.trustedCAs.path` BON constant (default
  `/trustedCAs.der`).

Signed application binaries consumed by this library are produced by the corresponding MicroEJ application
app-signer tool.

# Usage

Add the following dependency to your `build.gradle.kts`:

```kotlin
implementation("com.microej.library.util:app-verifier:x.y.z")
```

Verify a signed application and obtain its installable binary. `verify()` returns a
`SignedApplicationBinaryInputStream` already positioned on the application binary (the install-request
wrapper has been stripped). A custom certificate-chain validation policy
can be provided through the constructor:

```java
SignedApplicationVerifier verifier = new SignedApplicationVerifier(myCertificateChainValidator);
try {
    SignedApplicationBinaryInputStream applicationBinary = verifier.verify(signedApplicationStream);
    // Hand applicationBinary to your application installer; it is the installable binary.
    // ... the installer reads applicationBinary to the end ...
    applicationBinary.isVerified(); // throws InvalidSignatureException if the signature is invalid
    // The signature is confirmed: the installed application can be trusted.
} catch (InvalidSignatureException e) {
    // Invalid signature: reject the application (and roll back the installation if needed).
}
```

The default trust anchor is the certificate(s) loaded from `/trustedCAs.der` through
`DefaultCertificateChainValidator.fromResource()`.

> The signature is verified **lazily**: it is checked once the returned stream has been **fully consumed**
> (typically by the installer). Reading the stream may therefore write the application, possibly to
> persistent memory, **before** the signature is confirmed. Once the stream is fully consumed, call
> `isVerified()` to confirm the signature (it throws `InvalidSignatureException` if verification failed, or
> `IllegalStateException` if the stream has not been fully read yet) before trusting the installed
> application.

The table below lists the error message IDs reported by the library, their level, description and arguments.

|  ID  |  Level   |                       Description                       |                Arguments                 |
|------|----------|---------------------------------------------------------|------------------------------------------|
| - 2  |  SEVERE  |        The signed application format is not valid       |       None / Message of throwable        |
| - 3  |  SEVERE  |       The provided verifier version is not supported    |    Provided version, expected version    |
| - 4  |  SEVERE  |     The provided 'install' version is not supported     |    Provided version, expected version    |
| - 5  |  SEVERE  |    The provided signature algorithm is not supported    |               Provided OID               |
| - 6  |  SEVERE  |     The length of the input stream is inconsistent      | None / Provided length, expected length  |
| - 7  |  SEVERE  |               The signature is not valid                |           Message of throwable           |
| - 8  |  SEVERE  |     No trusted certificates are provided or matched     |       None / Message of throwable        |
| - 9  |  SEVERE  |      The verification of the signature has failed       |           Message of throwable           |
| - 10 |  SEVERE  |  The certificate chain was verified but not authorized  |                   None                   |

The following error message IDs are not raised by the library. They are reserved for integrator code that
supplies the trusted key or certificate to a `CertificateChainValidator` (for example a custom public-key
provider).

|  ID  |  Level   |                       Description                       |                Arguments                 |
|------|----------|---------------------------------------------------------|------------------------------------------|
| - 11 |  SEVERE  |      The provided key is null or not a public key       |                   None                   |
| - 12 |  SEVERE  |                 The certificate is null                 |                   None                   |

# Requirements

This library requires the following Foundation Libraries:

- EDC 1.3.7
- CRYPTO 2.0.1

# Dependencies

_All dependencies are retrieved transitively by Gradle_.

# Source

N/A.

# Restrictions

None.

---

_Copyright 2026 MicroEJ Corp._\
_Use of this source code is governed by a BSD-style license that can be found with this software._\
_Build: 7E4D1F7C_
