Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@
*/
package dev.sigstore.fulcio.client;

import dev.sigstore.fulcio.v2.CertificateChain;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

/** A client to communicate with a fulcio service instance. */
public interface FulcioClient {
Expand All @@ -26,4 +33,20 @@ public interface FulcioClient {

CertPath signingCertificate(CertificateRequest request)
throws InterruptedException, CertificateException;

static CertPath decodeCerts(CertificateChain certChain) throws CertificateException {
var certificateFactory = CertificateFactory.getInstance("X.509");
var certs = new ArrayList<X509Certificate>();
if (certChain.getCertificatesCount() == 0) {
throw new CertificateParsingException(
"no valid PEM certificates were found in response from Fulcio");
}
for (var cert : certChain.getCertificatesList()) {
certs.add(
(X509Certificate)
certificateFactory.generateCertificate(
new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8))));
}
return certificateFactory.generateCertPath(certs);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,18 @@
import static dev.sigstore.fulcio.v2.SigningCertificate.CertificateCase.SIGNED_CERTIFICATE_DETACHED_SCT;

import com.google.api.client.util.Preconditions;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import dev.sigstore.fulcio.v2.CAGrpc;
import dev.sigstore.fulcio.v2.CertificateChain;
import dev.sigstore.fulcio.v2.CreateSigningCertificateRequest;
import dev.sigstore.fulcio.v2.Credentials;
import dev.sigstore.fulcio.v2.PublicKey;
import dev.sigstore.fulcio.v2.PublicKeyRequest;
import dev.sigstore.http.GrpcChannels;
import dev.sigstore.http.HttpParams;
import dev.sigstore.trustroot.Service;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -125,25 +118,9 @@ public CertPath signingCertificate(CertificateRequest request)
if (certs.getCertificateCase() == SIGNED_CERTIFICATE_DETACHED_SCT) {
throw new CertificateException("Detached SCTs are not supported");
}
return decodeCerts(certs.getSignedCertificateEmbeddedSct().getChain());
return FulcioClient.decodeCerts(certs.getSignedCertificateEmbeddedSct().getChain());
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}

@VisibleForTesting
CertPath decodeCerts(CertificateChain certChain) throws CertificateException {
var certificateFactory = CertificateFactory.getInstance("X.509");
var certs = new ArrayList<X509Certificate>();
if (certChain.getCertificatesCount() == 0) {
throw new CertificateParsingException(
"no valid PEM certificates were found in response from Fulcio");
}
for (var cert : certChain.getCertificatesList().asByteStringList()) {
certs.add(
(X509Certificate)
certificateFactory.generateCertificate(new ByteArrayInputStream(cert.toByteArray())));
}
return certificateFactory.generateCertPath(certs);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* Copyright 2026 The Sigstore Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.sigstore.fulcio.client;

import static dev.sigstore.fulcio.v2.SigningCertificate.CertificateCase.SIGNED_CERTIFICATE_DETACHED_SCT;
import static dev.sigstore.fulcio.v2.SigningCertificate.CertificateCase.SIGNED_CERTIFICATE_EMBEDDED_SCT;

import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Preconditions;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import dev.sigstore.fulcio.v2.CreateSigningCertificateRequest;
import dev.sigstore.fulcio.v2.PublicKey;
import dev.sigstore.fulcio.v2.PublicKeyRequest;
import dev.sigstore.fulcio.v2.SigningCertificate;
import dev.sigstore.http.HttpClients;
import dev.sigstore.http.HttpParams;
import dev.sigstore.json.ProtoJson;
import dev.sigstore.trustroot.Service;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.util.Base64;
import java.util.Locale;

/** A client to communicate with a fulcio service instance over HTTP. */
public class FulcioClientHttp implements FulcioClient {
public static final String FULCIO_SIGNING_CERT_PATH = "/api/v2/signingCert";

private final HttpParams httpParams;
private final URI uri;

public static Builder builder() {
return new Builder();
}

private FulcioClientHttp(HttpParams httpParams, URI uri) {
this.uri = uri;
this.httpParams = httpParams;
}

public static class Builder {
private HttpParams httpParams = HttpParams.builder().build();
private Service service;

private Builder() {}

/** Configure the http properties, see {@link HttpParams}. */
public Builder setHttpParams(HttpParams httpParams) {
this.httpParams = httpParams;
return this;
}

/** Service information for a remote fulcio instance. */
public Builder setService(Service service) {
this.service = service;
return this;
}

public FulcioClientHttp build() {
Preconditions.checkNotNull(service);
return new FulcioClientHttp(httpParams, service.getUrl());
}
}

/**
* Request a signing certificate from fulcio over HTTP.
*
* @param request certificate request parameters
* @return a {@link CertPath} from fulcio
*/
@Override
public CertPath signingCertificate(CertificateRequest request) throws CertificateException {
URI endpoint = uri.resolve(FULCIO_SIGNING_CERT_PATH);

String pemEncodedPublicKey =
"-----BEGIN PUBLIC KEY-----\n"
+ Base64.getEncoder().encodeToString(request.getPublicKey().getEncoded())
+ "\n-----END PUBLIC KEY-----";

var createSigningCertificateRequest =
CreateSigningCertificateRequest.newBuilder()
.setPublicKeyRequest(
PublicKeyRequest.newBuilder()
.setPublicKey(
PublicKey.newBuilder()
.setAlgorithm(request.getPublicKeyAlgorithm())
.setContent(pemEncodedPublicKey)
.build())
.setProofOfPossession(ByteString.copyFrom(request.getProofOfPossession()))
.build())
.build();

String jsonPayload;
try {
jsonPayload = JsonFormat.printer().print(createSigningCertificateRequest);
} catch (InvalidProtocolBufferException e) {
throw new CertificateException("Failed to serialize certificate request", e);
}

String responseJson;
try {
var httpRequest =
HttpClients.newRequestFactory(httpParams)
.buildPostRequest(
new GenericUrl(endpoint),
ByteArrayContent.fromString("application/json", jsonPayload));
httpRequest.getHeaders().set("Accept", "application/json");
httpRequest.getHeaders().set("Content-Type", "application/json");
httpRequest.getHeaders().set("Authorization", "Bearer " + request.getIdToken());
httpRequest.setThrowExceptionOnExecuteError(false);

var resp = httpRequest.execute();
responseJson = resp.parseAsString();
if (resp.getStatusCode() != 200) {
throw new CertificateException(
String.format(
Locale.ROOT, "bad response from fulcio @ '%s' : %s", endpoint, responseJson));
}
} catch (IOException e) {
throw new CertificateException("Failed to request signing certificate from fulcio", e);
}

Comment thread
aaronlew02 marked this conversation as resolved.
var signingCertBuilder = SigningCertificate.newBuilder();
try {
ProtoJson.parser().merge(responseJson, signingCertBuilder);
} catch (InvalidProtocolBufferException e) {
throw new CertificateException("Failed to parse signing certificate response from fulcio", e);
}
var signingCert = signingCertBuilder.build();

if (signingCert.getCertificateCase() == SIGNED_CERTIFICATE_DETACHED_SCT) {
throw new CertificateException("Detached SCTs are not supported");
}
if (signingCert.getCertificateCase() != SIGNED_CERTIFICATE_EMBEDDED_SCT) {
throw new CertificateException("No certificate was found in response from fulcio");
}

return FulcioClient.decodeCerts(signingCert.getSignedCertificateEmbeddedSct().getChain());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022 The Sigstore Authors.
* Copyright 2026 The Sigstore Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,6 +15,8 @@
*/
package dev.sigstore.fulcio.client;

import static org.junit.jupiter.api.Named.named;

import com.google.common.io.Resources;
import dev.sigstore.AlgorithmRegistry;
import dev.sigstore.encryption.certificates.Certificates;
Expand All @@ -29,70 +31,78 @@
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

public class FulcioClientTest {

static Stream<org.junit.jupiter.api.Named<Function<FulcioWrapper, FulcioClient>>> clients() {
return Stream.of(
named(
"grpc",
w ->
FulcioClientGrpc.builder()
.setHttpParams(HttpParams.builder().allowInsecureConnections(true).build())
.setService(w.getGrpcService())
.build()),
named(
"http",
w ->
FulcioClientHttp.builder()
.setHttpParams(HttpParams.builder().allowInsecureConnections(true).build())
.setService(w.getHttpService())
.build()));
}

public class FulcioClientGrpcTest {

@Test
@ParameterizedTest
@MethodSource("clients")
@ExtendWith({FakeCTLogServer.class, MockOAuth2ServerExtension.class, FulcioWrapper.class})
public void testSigningCert(
MockOAuth2ServerExtension mockOAuthServerExtension, FulcioWrapper fulcioWrapper)
Function<FulcioWrapper, FulcioClient> clientFactory,
MockOAuth2ServerExtension mockOAuthServerExtension,
FulcioWrapper fulcioWrapper)
throws Exception {
// create a "subject" and sign it with the oidc server key (signed JWT)
var token = mockOAuthServerExtension.getOidcToken().getIdToken();
var subject = mockOAuthServerExtension.getOidcToken().getSubjectAlternativeName();

var signer = Signers.from(AlgorithmRegistry.SigningAlgorithm.PKIX_ECDSA_P256_SHA_256);
var signed = signer.sign(subject.getBytes(StandardCharsets.UTF_8));

// create a certificate request with our public key and our signed "subject"
var cReq = CertificateRequest.newCertificateRequest(signer.getPublicKey(), token, signed);
var sc = clientFactory.apply(fulcioWrapper).signingCertificate(cReq);

// ask fulcio for a signing cert
var client =
FulcioClientGrpc.builder()
.setHttpParams(HttpParams.builder().allowInsecureConnections(true).build())
.setService(fulcioWrapper.getGrpcService())
.build();

var sc = client.signingCertificate(cReq);

// some pretty basic assertions
Assertions.assertTrue(sc.getCertificates().size() > 0);
Assertions.assertTrue(Certificates.getEmbeddedSCTs(Certificates.getLeaf(sc)).isPresent());
}

@Test
@ParameterizedTest
@MethodSource("clients")
@ExtendWith({MockOAuth2ServerExtension.class, FulcioWrapper.class})
public void testSigningCert_NoSct(
MockOAuth2ServerExtension mockOAuthServerExtension, FulcioWrapper fulcioWrapper)
Function<FulcioWrapper, FulcioClient> clientFactory,
MockOAuth2ServerExtension mockOAuthServerExtension,
FulcioWrapper fulcioWrapper)
throws Exception {

// create a "subject" and sign it with the oidc server key (signed JWT)
var token = mockOAuthServerExtension.getOidcToken().getIdToken();
var subject = mockOAuthServerExtension.getOidcToken().getSubjectAlternativeName();

var signer = Signers.from(AlgorithmRegistry.SigningAlgorithm.PKIX_RSA_PKCS1V15_2048_SHA256);
var signed = signer.sign(subject.getBytes(StandardCharsets.UTF_8));

// create a certificate request with our public key and our signed "subject"
var cReq = CertificateRequest.newCertificateRequest(signer.getPublicKey(), token, signed);

// ask fulcio for a signing cert
var client =
FulcioClientGrpc.builder()
.setHttpParams(HttpParams.builder().allowInsecureConnections(true).build())
.setService(fulcioWrapper.getGrpcService())
.build();
var ex =
Assertions.assertThrows(CertificateException.class, () -> client.signingCertificate(cReq));
Assertions.assertThrows(
CertificateException.class,
() -> clientFactory.apply(fulcioWrapper).signingCertificate(cReq));
Assertions.assertEquals(ex.getMessage(), "Detached SCTs are not supported");
}

@Test
public void testDecode_embeddedGrpc() throws Exception {
@org.junit.jupiter.api.Test
public void testDecodeCerts() throws Exception {
var certs =
GrpcTypes.PemToCertificateChain(
Resources.toString(
Expand All @@ -104,10 +114,8 @@ public void testDecode_embeddedGrpc() throws Exception {
var signingConfig = tufClient.getSigstoreSigningConfig();
var fulcioService = Service.select(signingConfig.getCas(), List.of(1)).get();

var signingCert =
FulcioClientGrpc.builder().setService(fulcioService).build().decodeCerts(certs);
Assertions.assertTrue(
Certificates.getEmbeddedSCTs(Certificates.getLeaf(signingCert)).isPresent());
Assertions.assertEquals(3, signingCert.getCertificates().size());
var certPath = FulcioClient.decodeCerts(certs);
Assertions.assertTrue(Certificates.getEmbeddedSCTs(Certificates.getLeaf(certPath)).isPresent());
Assertions.assertEquals(3, certPath.getCertificates().size());
}
}
Loading
Loading