Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions google-auth-library-java/DEVELOPMENT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
# Development Guide

## Running Tests

Run unit tests from `google-auth-library-java`:

```bash
mvn test
```

## Dummy Test Certificates

Unit tests in `oauth2_http` use synthetic PEM-encoded X.509 certificates (Base64 text blocks starting with `-----BEGIN CERTIFICATE-----`) and unencrypted PKCS#8 private keys (`-----BEGIN PRIVATE KEY-----`) under `oauth2_http/testresources/`. Never commit real certificates or production private keys.

In a certificate chain, a root CA (Certificate Authority) signs an intermediate CA, which signs the leaf (client or server) certificate. Chains are ordered leaf-first.

### Prerequisites

- OpenSSL 3.5+ (current LTS, also compatible with OpenSSL 4.0+). Check with `openssl version`. On macOS, `/usr/bin/openssl` is LibreSSL, so install OpenSSL with `brew install openssl` and add `$(brew --prefix openssl)/bin` to `PATH`.
Comment thread
lqiu96 marked this conversation as resolved.
Resolved
- JDK `keytool` (included with the JDK) for inspecting multi-certificate PEM files with Java's X.509 parser.
- Commands below assume Linux or macOS. On Windows, replace `/dev/null` with `NUL`, and prefix `-subj` commands with `MSYS_NO_PATHCONV=1` in Git Bash.

### Some Existing Fixtures (`oauth2_http/testresources/`)

Reuse existing fixtures whenever a test only needs a valid certificate, key pair, trust chain, or SPIFFE certificate. Generate new ones only when a test needs a property not already covered, such as an extra rotation certificate, a different key algorithm, custom extensions or Subject Alternative Names (SANs), an expired certificate, or a custom CA hierarchy.

Below are some of the fixtures already in `oauth2_http/testresources/`:

| Files | Contents | Used For |
| --- | --- | --- |
| `x509_leaf_certificate.pem`, `x509_intermediate_certificate.pem`, `trust_chain_*.pem` | Self-signed RSA certs and concatenated chains (`with_leaf`, `without_leaf`, `wrong_order`) | X.509 Workload Identity Federation subject token and chain ordering tests |
| `mtls/test_cert.pem`, `mtls/test_key.pem`, `mtls/test_cert_2.pem`, `mtls/test_key_2.pem` | 100-year RSA 2048-bit cert/key pairs (PKCS#8) | Mutual TLS (mTLS) transport, Java `KeyStore`, rotation, and local socket tests |
| `mtls/test_chain_cert.pem`, `mtls/test_chain_key.pem` | Signed ECDSA P-256 leaf and intermediate CA chain + PKCS#8 key | Full certificate chain presentation tests (`MtlsKeyStoreUtilsTest`) |
| `mtlsCertAndKey.pem` | Combined cert and PKCS#8 key in one PEM file | Combined-bundle mTLS and non-agent cert tests |
| `agent/agent_spiffe_*.pem` | RSA/DSA certs with a `spiffe://` URI SAN, key, and chain | Agent Identity SPIFFE validation and bound token tests |
| `cert.pem` | Single self-signed RSA cert | GDCH (Google Distributed Cloud Hosted) CA certificate loading tests |

### Generating Dummy Certificates

Run these commands in a temporary directory (for example, `cd "$(mktemp -d)"`), then copy only the final fixture files you need into `oauth2_http/testresources/` and delete the temporary files.

#### 1. Self-Signed Cert and Key (single cert, mTLS pair, rotation cert, or combined bundle)

```bash
openssl req -x509 -newkey rsa:2048 -noenc \
-keyout test_key.pem \
-out test_cert.pem \
-days 36500 \
-subj "/CN=test-client"
```

Parameters:
- `req` (required): subcommand for CSRs (Certificate Signing Requests) and self-signed certificates
- `-x509` (required): output a self-signed X.509 certificate instead of a CSR
- `-newkey rsa:2048` (required unless passing `-key`): generate a new 2048-bit RSA private key
- `-noenc` (required for tests): leave the private key unencrypted (otherwise OpenSSL prompts for a passphrase and writes an encrypted key that the library rejects). Replaces deprecated `-nodes`.
- `-keyout test_key.pem` (optional): output path for the private key. If omitted, OpenSSL still writes `privkey.pem` in the current directory. Pass `-keyout /dev/null` if you do not need a key file.
- `-out test_cert.pem` (optional): output path for the certificate (defaults to stdout if omitted)
- `-days 36500` (optional, recommended): validity period in days (defaults to 30 days if omitted). Use 36500 (about 100 years) so certificates in real TLS tests (`MtlsPipelineLocalTest`) do not expire.
- `-subj "/CN=test-client"` (optional): certificate subject identity (`CN` is Common Name), passed inline so OpenSSL does not prompt interactively

Common variations:
- Cert only (no private key file needed, such as `x509_leaf_certificate.pem` or `cert.pem`): pass `-keyout /dev/null` instead of `-keyout test_key.pem`.
- Combined cert and key bundle (such as `mtlsCertAndKey.pem`):

```bash
cat test_cert.pem test_key.pem > combined_cert_and_key.pem
```

Private key format (PKCS#8): `MtlsKeyStoreUtils` and `OAuth2Utils.privateKeyFromPkcs8` require unencrypted PKCS#8 keys (`-----BEGIN PRIVATE KEY-----`). OpenSSL 3.5+ writes this format by default.
Comment thread
lqiu96 marked this conversation as resolved.
Resolved

If you have a key in a legacy format (PKCS#1 `-----BEGIN RSA PRIVATE KEY-----` or SEC1 `-----BEGIN EC PRIVATE KEY-----`), convert it to PKCS#8:

```bash
openssl pkcs8 -topk8 -nocrypt -in legacy_key.pem -out test_key.pem
```

Parameters:
- `-topk8` (required): convert the key to PKCS#8 format
- `-nocrypt` (required for tests): leave the output key unencrypted
- `-in` / `-out` (optional): input and output file paths (default to stdin and stdout)

#### 2. Concatenated Trust Chains (PEM parsing and ordering tests, no signature checks)

`CertificateIdentityPoolSubjectTokenSupplier` compares each certificate's raw binary (DER) bytes against the leaf certificate and checks that the leaf appears first or is omitted, without verifying parent signatures.

Run the command in [1. Self-Signed Cert and Key](#1-self-signed-cert-and-key-single-cert-mtls-pair-rotation-cert-or-combined-bundle) twice with `-keyout /dev/null` and distinct outputs and subjects (for example, `-out leaf_cert.pem -subj "/CN=test-leaf"` and `-out intermediate_cert.pem -subj "/CN=test-intermediate"` so the order is easy to inspect), then concatenate them:

```bash
cat leaf_cert.pem intermediate_cert.pem > trust_chain_with_leaf.pem # valid: leaf first
cp intermediate_cert.pem trust_chain_without_leaf.pem # valid: leaf omitted
cat intermediate_cert.pem leaf_cert.pem > trust_chain_wrong_order.pem # invalid: leaf not first
```

Required structure: each input must be a valid PEM `CERTIFICATE` block, and valid trust chains must place the leaf certificate first or omit it.

#### 3. Signed Certificate Chain (real CA signatures or full-chain Java `KeyStore` tests)

Matches the ECDSA P-256 chain in `mtls/test_chain_cert.pem` and `mtls/test_chain_key.pem`:

```bash
# 1. Root CA
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -noenc \
-keyout root_key.pem -out root_cert.pem -days 36500 \
-subj "/CN=Test Root CA" \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign"

# 2. Intermediate CA signed by Root CA
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -noenc \
-keyout intermediate_key.pem -out intermediate.csr \
-subj "/CN=Test Intermediate CA" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign"
openssl x509 -req -in intermediate.csr -CA root_cert.pem -CAkey root_key.pem \
-copy_extensions copy -out intermediate_cert.pem -days 36500

# 3. Leaf cert signed by Intermediate CA
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -noenc \
-keyout test_chain_key.pem -out leaf.csr \
-subj "/CN=Test Leaf" \
-addext "basicConstraints=critical,CA:FALSE" \
-addext "keyUsage=critical,digitalSignature" \
-addext "extendedKeyUsage=clientAuth" \
-addext "subjectAltName=URI:spiffe://example.test/workload"
openssl x509 -req -in leaf.csr -CA intermediate_cert.pem -CAkey intermediate_key.pem \
-copy_extensions copy -out leaf_cert.pem -days 36500

# 4. Bundle leaf and intermediate (leaf first, root CA omitted)
cat leaf_cert.pem intermediate_cert.pem > test_chain_cert.pem
```

Copy `test_chain_cert.pem` and `test_chain_key.pem` (and `root_cert.pem` only if a test explicitly verifies against a root trust anchor) into `oauth2_http/testresources/`, then delete the remaining scratch files (`*.csr`, CA keys, and individual certs). Client chains normally omit the root CA.

Additional parameters beyond [1. Self-Signed Cert and Key](#1-self-signed-cert-and-key-single-cert-mtls-pair-rotation-cert-or-combined-bundle):
- `-newkey ec -pkeyopt ec_paramgen_curve:prime256v1` (required for ECDSA): generate a NIST P-256 elliptic curve key (substitute `rsa:2048` for RSA)
- `-addext "basicConstraints=critical,CA:TRUE"` (required on CAs): marks the certificate as a CA so chain verification accepts it
- `-addext "keyUsage=..."` / `"extendedKeyUsage=..."` / `"subjectAltName=..."` (optional): sets key usage, Extended Key Usage (EKU), or SAN extensions when tests check them
- `x509 -req -in <csr>` (required): sign a CSR to issue a certificate
- `-CA <cert>` and `-CAkey <key>` (required): signing CA certificate and private key
- `-copy_extensions copy` (required when the CSR carries `-addext` extensions): copies extensions from the CSR onto the signed certificate

#### 4. SPIFFE Cert with URI SAN (Agent Identity tests)

Include a `spiffe://<trust-domain>/<path>` workload identity URI whose trust domain (host portion) matches a pattern in `AgentIdentityCertificateValidationUtils` (such as `agents.global.proj-<digits>.system.id.goog`):

```bash
openssl req -x509 -newkey rsa:2048 -noenc \
-keyout agent_spiffe_key.pem \
-out agent_spiffe_cert.pem \
-days 36500 \
-subj "/CN=Test SPIFFE Certificate" \
-addext "subjectAltName=URI:spiffe://agents.global.proj-12345.system.id.goog/test-workload"
```

Uses the same required and optional parameters as [1. Self-Signed Cert and Key](#1-self-signed-cert-and-key-single-cert-mtls-pair-rotation-cert-or-combined-bundle), plus:
- `-addext "subjectAltName=URI:spiffe://..."` (required): adds the SPIFFE URI SAN checked by `AgentIdentityCertificateValidationUtils`

Pass `-keyout /dev/null` if the test only loads the certificate. For a signed SPIFFE chain, use [3. Signed Certificate Chain](#3-signed-certificate-chain-real-ca-signatures-or-full-chain-java-keystore-tests) with this `subjectAltName` on the leaf.

### Decoding and Debugging PEM Certificates

Run the fixture commands below from `google-auth-library-java/`. Note that `openssl x509` only reads the first certificate in a multi-cert PEM file.

Inspect certificates and chains:

```bash
# Single cert summary (subject, issuer, dates, SHA-256 fingerprint)
openssl x509 -in oauth2_http/testresources/x509_leaf_certificate.pem \
-noout -subject -issuer -dates -fingerprint -sha256

# Single cert full text (extensions, SANs, key details)
openssl x509 -in oauth2_http/testresources/agent/agent_spiffe_cert.pem -noout -text

# All certs in a cert-only multi-cert PEM using Java's parser (recommended for chains; fails if a private key is in the file)
# Expect Certificate[1] to be the leaf, and for signed chains Certificate[1]'s Issuer to match Certificate[2]'s Owner
keytool -printcert -file oauth2_http/testresources/trust_chain_with_leaf.pem

# All certs in any PEM file with OpenSSL, including combined cert+key bundles (append -text for full fields)
openssl crl2pkcs7 -nocrl -certfile oauth2_http/testresources/trust_chain_with_leaf.pem \
| openssl pkcs7 -print_certs -noout
```

Verify key pairs, chains, and subject tokens:

```bash
# Check cert matches private key (RSA or EC). Both commands should print the exact same SHA-256 hash.
# For a combined cert+key file (mtlsCertAndKey.pem), pass the same path to both commands.
openssl x509 -in oauth2_http/testresources/mtls/test_cert.pem -pubkey -noout | openssl sha256
openssl pkey -in oauth2_http/testresources/mtls/test_key.pem -pubout | openssl sha256

# Verify a signed chain before deleting the scratch files from section 3 (expect "leaf_cert.pem: OK")
# Intentionally self-signed certs from sections 1 and 2 will fail verification.
openssl verify -CAfile root_cert.pem -untrusted intermediate_cert.pem leaf_cert.pem

# Same check when only the intermediate CA is available
openssl verify -partial_chain -trusted intermediate_cert.pem leaf_cert.pem

# Decode one Base64 DER entry from the JSON array returned by CertificateIdentityPoolSubjectTokenSupplier
# Strip surrounding quotes from the JSON string first.
printf '%s' "<base64-der-string>" | openssl base64 -d -A | openssl x509 -inform DER -noout -text
```

### Troubleshooting

| Symptom | Likely Cause | Check |
| --- | --- | --- |
| `private key is missing from certAndKey string` | Key is missing, encrypted (`BEGIN ENCRYPTED PRIVATE KEY`), or uses legacy PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`) instead of PKCS#8 (`BEGIN PRIVATE KEY`) | `grep "BEGIN " <file.pem>`, then convert legacy keys with `openssl pkcs8 -topk8 -nocrypt` |
| `Certificate and private key do not match` | Private key does not match the first certificate's public key, or a chain file does not put the leaf certificate first | Compare public key SHA-256 hashes above, and check chain order with `keytool -printcert` |
| `The leaf certificate should only appear at the beginning of the trust chain file, or be omitted entirely.` | Leaf cert appears after another cert in the trust chain PEM | `keytool -printcert -file <chain.pem>` (expect `Certificate[1]` to be the leaf, or leaf omitted) |
| TLS handshake fails with expired cert | `notAfter` date passed (hits real TLS tests like `MtlsPipelineLocalTest`) | `openssl x509 -in <cert.pem> -noout -dates` (or `keytool -printcert` for chains), then regenerate with `-days 36500` |
| Agent identity tests skip token binding | Missing or non-matching `URI:spiffe://` SAN | `openssl x509 -in <cert.pem> -noout -ext subjectAltName` (expect `URI:spiffe://...`) |
Loading