Skip to content

Harden constitution validation for JWT, CA, and member keys#7924

Open
Copilot wants to merge 27 commits into
mainfrom
copilot/fix-constitution-validators-strictness
Open

Harden constitution validation for JWT, CA, and member keys#7924
Copilot wants to merge 27 commits into
mainfrom
copilot/fix-constitution-validators-strictness

Conversation

Copilot AI commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Constitution validators accepted weak or malformed security inputs, including unsafe JWKS metadata, non-HTTPS JWT issuers, non-root-CA TLS trust anchors, and unchecked member encryption keys. This tightens validation using the existing JS crypto surface where available.

  • JWKS validation
    • Require unique kid values.
    • Restrict kty to RSA or EC.
    • Restrict use to sig.
    • Restrict alg to supported signing algorithms (RS256, ES256).
    • Validate RSA/EC public key parameters, including P-256, P-384, and P-521 EC curves, and reject weak RSA keys.
    • Validate x5c certificate chains to the provided root.
checkEnum(jwk.kty, ["RSA", "EC"], `${keyField}.kty`);
checkEnum(jwk.alg, jwk.kty === "RSA" ? ["RS256"] : ["ES256"], `${keyField}.alg`);
checkEnum(jwk.use, ["sig"], `${keyField}.use`);
  • JWT issuer validation

    • Require all JWT issuers to be HTTPS URLs.
    • Reject issuers with query strings or fragments, regardless of auto_refresh.
  • CA bundle validation

    • set_ca_cert_bundle now requires every certificate in the bundle to be a self-signed (root) CA. Intermediate CA certificates are rejected even when their signing root is also present in the bundle.
    • Added isValidX509RootCACert to the JS crypto API (ccf.crypto), backed by a C++ function that checks both EXFLAG_SS (self-signed) and X509_check_ca, without relying on X509_V_FLAG_PARTIAL_CHAIN.
  • Member encryption key validation

    • set_member now validates encryption_pub_key as a well-formed RSA public key with minimum strength before storing it.
  • P-521 support

    • Added P-521 JWK/PEM curve mapping support in the existing crypto surface used by validation.
    • Extended related JS crypto and C++ crypto tests for P-521 coverage.
  • Coverage updates

    • Added focused governance validation cases for rejected JWT issuer/JWKS inputs.
    • Added rejection coverage for non-CA and intermediate CA certificate bundles.
    • Updated JWT test certificate generation and docs to satisfy stricter validation.
    • Added polyfill tests for isValidX509RootCACert (self-signed CA, non-CA self-signed, intermediate CA, malformed input).

Copilot AI changed the title [WIP] Fix insufficient strictness in constitution validators Harden constitution validation for JWT, CA, and member keys Jun 5, 2026
Copilot AI requested a review from achamayou June 5, 2026 12:40
Comment thread samples/constitutions/default/actions.js Outdated
Comment thread samples/minimal_ccf/app/actions.js Outdated
@achamayou

Copy link
Copy Markdown
Member

@copilot add a relevant changelog entry

Copilot AI commented Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

@copilot add a relevant changelog entry

Added the changelog entry in bdfdd14.

@achamayou achamayou added this to the 7.0.5 milestone Jun 5, 2026
achamayou and others added 4 commits June 5, 2026 18:32
- Use ceiling division when sizing EC coordinate/private-scalar buffers so curves whose bit-size is not a multiple of 8 (P-521 has 521 bits) get the full 66-byte buffer rather than a truncated 65-byte one. This fixes BN_bn2binpad failures and dropped leading-zero bytes when round-tripping P-521 keys through JWK.

- Update test_jwt_auth_raw_key to use an https:// JWT issuer URL so it satisfies the hardened set_jwt_issuer constitution validator added in this PR.

- Run clang-format on curve.h and crypto.cpp.
achamayou and others added 5 commits June 8, 2026 18:46
RFC 7518 requires JWK numeric fields to be base64url-encoded. The new checkBase64Url validator in the hardened constitution rejects standard base64 (with + or /), which caused the authn e2e test to fail when registering a JwtIssuer raw key whose modulus happened to encode to a byte sequence containing those characters.
Two correctness fixes to the new constitution validators:

1. checkX509CACertBundle previously required every cert in the bundle to be self-signed (chain-to-self), which rejected the common case of an intermediate CA signed by a root CA also in the bundle (typical for real-world IdPs). Validate each cert against the whole bundle instead, which still enforces 'all certs are CAs' (verify_certificate calls X509_check_ca on every trusted cert) while accepting intermediates via X509_V_FLAG_PARTIAL_CHAIN.

2. checkJwks's alg enum allowed any RSA key to claim RS256 and any EC key to claim ES256, even when the crv was P-384 or P-521. Per RFC 7518 section 3.4 each ES* alg binds to a specific curve, so gate the EC alg list on jwk.crv when present (ES256/P-256, ES384/P-384, ES512/P-521). When only x5c is supplied and crv is absent, accept any of the supported ES* algorithms.

Add e2e coverage in tests/ca_certs.py (intermediate+root bundle accepted) and tests/jwt_test.py (RSA key with ES256 rejected; EC P-256 key with ES384/ES512/RS256 rejected).
- checkRsaPublicKey: call checkBase64Url explicitly on e (rather than discarding the byte-length result) and explain why a 256-byte n is a sufficient proxy for a >=2048-bit modulus per RFC 7518 section 6.3.1.1.

- splitX509CertBundle: drop the dead items.length === 1 branch and document that leading whitespace on intermediate certs is tolerated by the OpenSSL PEM parser.

- CHANGELOG: move the constitution-validator note from Fixed to Changed and enumerate the operator-visible rejections (https-only issuer, CA-only bundles, base64url-only n/e/x/y, kty/key-material binding, kid uniqueness, use=sig, RFC 7518 section 3.4 alg-vs-curve binding, RSA >=2048 bits, RFC 7518 section 6.2.1.2 EC coordinate length, P-521 support).
- Break the single 14-line constitution-validator bullet into four focused bullets, one per affected proposal action, so each operator-visible behaviour change is independently scannable.

- to_b64: correct the RFC citation. Base64url is defined in RFC 4648 section 5; RFC 7518 section 6 only references it for JWK numeric fields.
The constitution-validator changes ship in 7.0.5, not 7.0.4. Move the four bullets into a new Changed section under 7.0.5.
@achamayou achamayou marked this pull request as ready for review June 8, 2026 20:11
@achamayou achamayou requested a review from a team as a code owner June 8, 2026 20:11
Copilot AI review requested due to automatic review settings June 8, 2026 20:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens governance constitution validation for JWT issuers/JWKS inputs, CA certificate bundles, and member encryption keys, and extends crypto support to include P-521 across the JS and C++ crypto surfaces. It updates end-to-end/unit tests and documentation to match the stricter validation rules and new curve support.

Changes:

  • Tighten sample constitution validation for JWT issuer URLs, JWKS key material/metadata, CA bundles, and member encryption_pub_key.
  • Add P-521 (secp521r1) support across crypto conversion/mapping layers and extend related JS/C++ tests.
  • Update test infrastructure and docs to generate/expect HTTPS issuers and CA-capable certificates where required by new validation.

Custom instructions used:

  • .github/copilot-instructions.md
  • .github/instructions/reviewing.instructions.md

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/npm_tests.py Extends EC keypair/JWK tests to include P-521.
tests/jwt_test.py Adds negative-coverage tests for stricter JWT issuer URL and JWKS validation.
tests/js-custom-authorization/custom_authorization.py Updates test issuer URL to HTTPS to satisfy new issuer validation.
tests/infra/jwt_issuer.py Switches JWK numeric encoding to base64url and generates CA-capable certs for JWT issuer fixtures.
tests/ca_certs.py Adds rejection/acceptance cases for CA bundle validation (non-CA and intermediate/root bundles).
src/js/extensions/ccf/crypto.cpp Adds secp521r1 mapping support in the JS crypto extension.
src/crypto/test/crypto.cpp Extends PEM↔JWK and COSE-compatibility tests to cover P-521.
src/crypto/openssl/ec_public_key.cpp Adds P-521 OpenSSL curve mapping and fixes coordinate sizing for non-byte-aligned curves.
src/crypto/openssl/ec_key_pair.cpp Fixes private-key coordinate sizing for non-byte-aligned curves (P-521).
samples/minimal_ccf/app/actions.js Adds stricter JWT/JWKS/CA/member-key validation to the minimal sample constitution.
samples/constitutions/default/actions.js Adds stricter JWT/JWKS/CA/member-key validation to the default constitution.
js/ccf-app/test/polyfill.test.ts Adds/extends tests for secp521r1 keygen and PEM↔JWK conversions.
js/ccf-app/src/global.ts Updates public TS typings/docs to mention secp521r1 support.
include/ccf/crypto/jwk.h Enables P-521 JWK curve mapping in C++ helpers.
include/ccf/crypto/curve.h Adds SECP521R1 to the supported curve enum and associated digest mapping.
doc/build_apps/auth/jwt.rst Updates JWT governance examples to use HTTPS issuer URLs.
CHANGELOG.md Documents the strengthened validation behavior and P-521 acceptance.
Comments suppressed due to low confidence (1)

src/crypto/openssl/ec_public_key.cpp:327

  • BN_bn2binpad() return values are ignored when serialising EC public key coordinates. If BN_bn2binpad fails (eg if OpenSSL returns an error), this will silently return incorrect x/y bytes rather than failing fast. Per the repo's third-party error-handling guidance, OpenSSL calls that can fail should have their return values checked (see .github/instructions/reviewing.instructions.md).
    int sz = (EC_GROUP_get_degree(group) + CHAR_BIT - 1) / CHAR_BIT;
    r.x.resize(sz);
    r.y.resize(sz);
    BN_bn2binpad(x, r.x.data(), sz);
    BN_bn2binpad(y, r.y.data(), sz);

Comment thread CHANGELOG.md
Comment on lines +110 to +121
function splitX509CertBundle(value) {
// Split on the END marker, drop the trailing post-marker remainder (empty
// for a well-formed bundle), and re-append the END marker to each cert.
// Note that intermediate certs may still carry a leading newline (or other
// separator whitespace) from the original concatenation; this is fine
// because the OpenSSL PEM parser is tolerant of leading whitespace.
const sep = "-----END CERTIFICATE-----";
return value
.split(sep)
.slice(0, -1)
.map((p) => p + sep);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems possibly error prone?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a specific error in mind?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot can you propose a way to make this less error prone?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original splitX509CertBundle was error-prone because it:

  • Silently accepted empty strings (returned [])
  • Created invalid cert fragments from malformed input (e.g., ["-----END CERTIFICATE-----"] from just an END marker)
  • Could include junk content in extracted certificates

The improved version in 0be62b0 uses regex pattern matching to:

  • Require both BEGIN and END certificate markers
  • Reject empty strings and malformed input with clear error messages
  • Reject bundles containing non-whitespace junk between certificates
  • Only return complete, valid PEM blocks

Comment on lines +125 to +131
// isValidX509CertChain(target, trusted) is backed by verify_certificate(),
// which (a) rejects the call outright if any cert in `trusted` is not a CA
// (via X509_check_ca), and (b) enables X509_V_FLAG_PARTIAL_CHAIN so that
// intermediate CAs can act as trust anchors. By passing the whole bundle as
// `trusted`, we therefore enforce that every cert in the bundle is a CA
// certificate, while still accepting bundles containing intermediates as
// well as roots.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is meant to check the chain, this will cause us to trust an intermediate blindly.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it won't, this is only a data validation call, it's never used for certification path resolution (done by OpenSSL in the OIDC client). We could restrict the bundle to be a set of roots though, and not allow partial chains, and I agree that probably covers all existing use cases.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot tighten this check and the comment to only allow the bundle to contain roots/CAs, no intermediate. Adjust tests accordingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tightened in the latest commits. The approach is:

  1. Added isValidX509RootCACert(pem) to the C++ JS crypto API — it checks both is_self_signed() (OpenSSL EXFLAG_SS) and X509_check_ca (via verify_certificate). This correctly rejects intermediate CAs regardless of whether their root is present in the bundle, without relying on X509_V_FLAG_PARTIAL_CHAIN.

  2. checkX509CACertBundle in both sample constitutions now calls isValidX509RootCACert for each certificate instead of isValidX509CertChain(cert, wholeBundle). The comment was updated accordingly.

  3. tests/ca_certs.py was updated to expect the "intermediate CA + root in bundle" case to be rejected.

TypeScript type declaration, polyfill implementation, and polyfill tests (including a proper intermediate-CA fixture) were also added.

@achamayou achamayou requested a review from cjen1-msft June 9, 2026 19:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Constitution validators are insufficiently strict

4 participants