Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] adding user defined subjects to run/sign #385

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions attestation/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package attestation
import (
"encoding/json"
"fmt"
"strings"
"time"

"github.com/in-toto/go-witness/cryptoutil"
Expand Down Expand Up @@ -145,6 +146,8 @@ func (c *Collection) Materials() map[string]cryptoutil.DigestSet {

func (c *Collection) BackRefs() map[string]cryptoutil.DigestSet {
backRefs := make(map[string]cryptoutil.DigestSet)

// Iterate over attestations and add back references from each attestation if it implements BackReffer
for _, attestation := range c.Attestations {
if backReffer, ok := attestation.Attestation.(BackReffer); ok {
for backRef, digest := range backReffer.BackRefs() {
Expand All @@ -153,5 +156,12 @@ func (c *Collection) BackRefs() map[string]cryptoutil.DigestSet {
}
}

// Iterate over the collection's subjects and add user-defined subjects as back references
for subj, ds := range c.Subjects() {
if strings.HasPrefix(subj, "user:") {
backRefs[subj] = ds
}
}

return backRefs
}
21 changes: 14 additions & 7 deletions dsse/sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,34 @@ import (
"github.com/in-toto/go-witness/timestamp"
)

type signOptions struct {
signers []cryptoutil.Signer
timestampers []timestamp.Timestamper
type SignOptions struct {
signers []cryptoutil.Signer
timestampers []timestamp.Timestamper
UserDefinedSubject map[string]cryptoutil.DigestSet
}

type SignOption func(*signOptions)
type SignOption func(*SignOptions)

func SignWithSigners(signers ...cryptoutil.Signer) SignOption {
return func(so *signOptions) {
return func(so *SignOptions) {
so.signers = signers
}
}

func SignWithTimestampers(timestampers ...timestamp.Timestamper) SignOption {
return func(so *signOptions) {
return func(so *SignOptions) {
so.timestampers = timestampers
}
}

func SignWithUserDefinedSubject(subject map[string]cryptoutil.DigestSet) SignOption {
return func(so *SignOptions) {
so.UserDefinedSubject = subject
}
}

func Sign(bodyType string, body io.Reader, opts ...SignOption) (Envelope, error) {
so := &signOptions{}
so := &SignOptions{}
env := Envelope{}
for _, opt := range opts {
opt(so)
Expand Down
57 changes: 44 additions & 13 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,15 @@ import (
"github.com/in-toto/go-witness/timestamp"
)

// runOptions struct now includes userDefinedSubject for user-defined subjects
type runOptions struct {
stepName string
signers []cryptoutil.Signer
attestors []attestation.Attestor
attestationOpts []attestation.AttestationContextOption
timestampers []timestamp.Timestamper
insecure bool
stepName string
signers []cryptoutil.Signer
attestors []attestation.Attestor
attestationOpts []attestation.AttestationContextOption
timestampers []timestamp.Timestamper
insecure bool
userDefinedSubject map[string]cryptoutil.DigestSet // Added user-defined subject field
}

type RunOption func(ro *runOptions)
Expand Down Expand Up @@ -78,6 +80,13 @@ func RunWithSigners(signers ...cryptoutil.Signer) RunOption {
}
}

// RunWithUserDefinedSubject allows users to define a subject for the attestation.
func RunWithUserDefinedSubject(subject map[string]cryptoutil.DigestSet) RunOption {
return func(ro *runOptions) {
ro.userDefinedSubject = subject
}
}

// RunResult contains the generated attestation collection as well as the signed DSSE envelope, if one was
// created.
type RunResult struct {
Expand All @@ -102,7 +111,9 @@ func RunWithExports(stepName string, opts ...RunOption) ([]RunResult, error) {
return run(stepName, opts)
}

// run function processes the attestation creation with provided options.
func run(stepName string, opts []RunOption) ([]RunResult, error) {
// Initialize runOptions with defaults and apply provided RunOptions
ro := runOptions{
stepName: stepName,
insecure: false,
Expand All @@ -112,11 +123,12 @@ func run(stepName string, opts []RunOption) ([]RunResult, error) {
opt(&ro)
}

result := []RunResult{}
var result []RunResult
if err := validateRunOpts(ro); err != nil {
return result, err
}

// Create attestation context
runCtx, err := attestation.NewContext(stepName, ro.attestors, ro.attestationOpts...)
if err != nil {
return result, fmt.Errorf("failed to create attestation context: %w", err)
Expand All @@ -126,6 +138,7 @@ func run(stepName string, opts []RunOption) ([]RunResult, error) {
return result, fmt.Errorf("failed to run attestors: %w", err)
}

// Process completed attestors
errs := make([]error, 0)
for _, r := range runCtx.CompletedAttestors() {
if r.Error != nil {
Expand All @@ -137,7 +150,15 @@ func run(stepName string, opts []RunOption) ([]RunResult, error) {
continue
}
if subjecter, ok := r.Attestor.(attestation.Subjecter); ok {
envelope, err := createAndSignEnvelope(r.Attestor, r.Attestor.Type(), subjecter.Subjects(), dsse.SignWithSigners(ro.signers...), dsse.SignWithTimestampers(ro.timestampers...))
// Merge user-defined subjects if provided
subjects := subjecter.Subjects()
if len(ro.userDefinedSubject) > 0 {
for k, v := range ro.userDefinedSubject {

subjects[k] = v
}
}
envelope, err := createAndSignEnvelope(r.Attestor, r.Attestor.Type(), subjects, dsse.SignWithSigners(ro.signers...), dsse.SignWithTimestampers(ro.timestampers...))
if err != nil {
return result, fmt.Errorf("failed to sign envelope: %w", err)
}
Expand All @@ -148,14 +169,24 @@ func run(stepName string, opts []RunOption) ([]RunResult, error) {
}

if len(errs) > 0 {
errs := append([]error{errors.New("attestors failed with error messages")}, errs...)
errs = append([]error{errors.New("attestors failed with error messages")}, errs...)
return result, errors.Join(errs...)
}

var collectionResult RunResult
collectionResult.Collection = attestation.NewCollection(ro.stepName, runCtx.CompletedAttestors())
// Final attestation collection with the user-defined subjects if provided
collectionResult := RunResult{
Collection: attestation.NewCollection(ro.stepName, runCtx.CompletedAttestors()),
}

// Sign collection if not in insecure mode
if !ro.insecure {
collectionResult.SignedEnvelope, err = createAndSignEnvelope(collectionResult.Collection, attestation.CollectionType, collectionResult.Collection.Subjects(), dsse.SignWithSigners(ro.signers...), dsse.SignWithTimestampers(ro.timestampers...))
collectionSubjects := collectionResult.Collection.Subjects()
if len(ro.userDefinedSubject) > 0 {
for k, v := range ro.userDefinedSubject {
collectionSubjects[k] = v
}
}
collectionResult.SignedEnvelope, err = createAndSignEnvelope(collectionResult.Collection, attestation.CollectionType, collectionSubjects, dsse.SignWithSigners(ro.signers...), dsse.SignWithTimestampers(ro.timestampers...))
if err != nil {
return result, fmt.Errorf("failed to sign collection: %w", err)
}
Expand All @@ -171,7 +202,7 @@ func validateRunOpts(ro runOptions) error {
}

if len(ro.signers) == 0 && !ro.insecure {
return fmt.Errorf("at lease one signer is required if not in insecure mode")
return fmt.Errorf("at least one signer is required if not in insecure mode")
}

return nil
Expand Down
116 changes: 100 additions & 16 deletions sign.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,116 @@
// Copyright 2021 The Witness Contributors
//
// 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 witness

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"

"github.com/in-toto/go-witness/cryptoutil"
"github.com/in-toto/go-witness/dsse"
"github.com/in-toto/go-witness/intoto"
"github.com/in-toto/go-witness/log"
)

// Sign parses the input, conditionally adds a user-defined subject for in-toto attestations, and then signs the DSSE envelope.
func Sign(r io.Reader, dataType string, w io.Writer, opts ...dsse.SignOption) error {
env, err := dsse.Sign(dataType, r, opts...)
// Create an instance of signOptions with defaults and apply provided SignOptions
so := &dsse.SignOptions{}
for _, opt := range opts {
opt(so)
}

// Check if user-defined subject is provided
hasUserDefinedSubject := len(so.UserDefinedSubject) > 0

// Parse the input payload
var rawPayload map[string]interface{}
if err := json.NewDecoder(r).Decode(&rawPayload); err != nil {
return fmt.Errorf("failed to decode input payload: %w", err)
}

// Check if the payload is an in-toto statement
if rawPayload["_type"] == "https://in-toto.io/Statement/v0.1" {
log.Info("payload is in-toto")
dataType := intoto.PayloadType

// Convert rawPayload to a Statement
stmt := intoto.Statement{}
payloadBytes, err := json.Marshal(rawPayload)
if err != nil {
return fmt.Errorf("failed to marshal payload to bytes: %w", err)
}
if err := json.Unmarshal(payloadBytes, &stmt); err != nil {
return fmt.Errorf("failed to unmarshal in-toto statement: %w", err)
}

for name, ds := range so.UserDefinedSubject {
s, err := intoto.DigestSetToSubject(name, ds)
if err != nil {
log.Errorf("failed to convert digest set to subject: %v", err)
}

stmt.Subject = append(stmt.Subject, s)

}

// Marshal the modified statement
finalPayload := stmt

// Create and sign envelope with subjects
envelope, err := createAndSignEnvelopeWithSubject(finalPayload, dataType, so.UserDefinedSubject, opts...)
if err != nil {
return fmt.Errorf("failed to create and sign envelope: %w", err)
}

// Encode the signed envelope to output writer w
encoder := json.NewEncoder(w)
return encoder.Encode(&envelope)
}

// Handle non-in-toto statements
if hasUserDefinedSubject {
return errors.New("user-defined subject is only allowed for in-toto statements")
}

envelope, err := dsse.Sign(dataType, r, opts...)
if err != nil {
return err
}

encoder := json.NewEncoder(w)
return encoder.Encode(&env)
return encoder.Encode(&envelope)
}

// Helper function to create and sign a DSSE envelope without double-wrapping
func createAndSignEnvelopeWithSubject(payload interface{}, dataType string, subjects map[string]cryptoutil.DigestSet, opts ...dsse.SignOption) (dsse.Envelope, error) {
var stmt intoto.Statement

// Check if payload is already an intoto statement
payloadBytes, err := json.Marshal(payload)
if err != nil {
return dsse.Envelope{}, fmt.Errorf("failed to marshal payload: %w", err)
}
if err := json.Unmarshal(payloadBytes, &stmt); err == nil && stmt.Type == "https://in-toto.io/Statement/v0.1" {
// Append user-defined subjects to existing in-toto statement
for name, ds := range subjects {
s, err := intoto.DigestSetToSubject(name, ds)
if err != nil {
return dsse.Envelope{}, fmt.Errorf("failed to convert digest set to subject: %w", err)
}
stmt.Subject = append(stmt.Subject, s)
}
} else {
// Handle error or create new statement if payload is not an in-toto statement
return dsse.Envelope{}, errors.New("payload is not a valid in-toto statement")
}

// Marshal the modified statement and sign without re-wrapping
stmtJson, err := json.Marshal(&stmt)
if err != nil {
return dsse.Envelope{}, fmt.Errorf("failed to marshal intoto statement: %w", err)
}

return dsse.Sign(dataType, bytes.NewReader(stmtJson), opts...)
}
Loading