cubefs
77 строк · 2.3 Кб
1// +build !appengine
2
3/*
4*
5* Copyright 2020 gRPC authors.
6*
7* Licensed under the Apache License, Version 2.0 (the "License");
8* you may not use this file except in compliance with the License.
9* You may obtain a copy of the License at
10*
11* http://www.apache.org/licenses/LICENSE-2.0
12*
13* Unless required by applicable law or agreed to in writing, software
14* distributed under the License is distributed on an "AS IS" BASIS,
15* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16* See the License for the specific language governing permissions and
17* limitations under the License.
18*
19*/
20
21// Package credentials defines APIs for parsing SPIFFE ID.
22//
23// All APIs in this package are experimental.
24package credentials25
26import (27"crypto/tls"28"crypto/x509"29"net/url"30
31"google.golang.org/grpc/grpclog"32)
33
34var logger = grpclog.Component("credentials")35
36// SPIFFEIDFromState parses the SPIFFE ID from State. If the SPIFFE ID format
37// is invalid, return nil with warning.
38func SPIFFEIDFromState(state tls.ConnectionState) *url.URL {39if len(state.PeerCertificates) == 0 || len(state.PeerCertificates[0].URIs) == 0 {40return nil41}42return SPIFFEIDFromCert(state.PeerCertificates[0])43}
44
45// SPIFFEIDFromCert parses the SPIFFE ID from x509.Certificate. If the SPIFFE
46// ID format is invalid, return nil with warning.
47func SPIFFEIDFromCert(cert *x509.Certificate) *url.URL {48if cert == nil || cert.URIs == nil {49return nil50}51var spiffeID *url.URL52for _, uri := range cert.URIs {53if uri == nil || uri.Scheme != "spiffe" || uri.Opaque != "" || (uri.User != nil && uri.User.Username() != "") {54continue55}56// From this point, we assume the uri is intended for a SPIFFE ID.57if len(uri.String()) > 2048 {58logger.Warning("invalid SPIFFE ID: total ID length larger than 2048 bytes")59return nil60}61if len(uri.Host) == 0 || len(uri.Path) == 0 {62logger.Warning("invalid SPIFFE ID: domain or workload ID is empty")63return nil64}65if len(uri.Host) > 255 {66logger.Warning("invalid SPIFFE ID: domain length larger than 255 characters")67return nil68}69// A valid SPIFFE certificate can only have exactly one URI SAN field.70if len(cert.URIs) > 1 {71logger.Warning("invalid SPIFFE ID: multiple URI SANs")72return nil73}74spiffeID = uri75}76return spiffeID77}
78