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

feat: add tspclient package #18

Merged
merged 53 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 46 commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
88866f4
added timestamp package
Two-Hearts Jan 19, 2024
33f5952
updated dependency
Two-Hearts Jan 19, 2024
86b9b3b
updated to tspclient
Two-Hearts Jan 22, 2024
8598d91
clean up
Two-Hearts Jan 22, 2024
5453b96
Merge branch 'notaryproject:main' into timestamp
Two-Hearts Jan 22, 2024
11e03e9
update
Two-Hearts Jan 22, 2024
0532d52
debug
Two-Hearts Jan 22, 2024
018c547
update
Two-Hearts Jan 22, 2024
2bc44d9
fix license
Two-Hearts Jan 22, 2024
5f0e2cc
update
Two-Hearts Jan 23, 2024
50ddae5
update
Two-Hearts Jan 24, 2024
55fba00
updated pki
Two-Hearts Jan 29, 2024
3fbb0c0
update
Two-Hearts Jan 29, 2024
ba59581
resolved conflicts
Two-Hearts Jan 31, 2024
820929d
Merge branch 'notaryproject:main' into timestamp
Two-Hearts Feb 1, 2024
45076e8
updated per code review
Two-Hearts Feb 1, 2024
c331596
update based on cms
Two-Hearts Mar 22, 2024
e3e90a5
added nonce check in response
Two-Hearts Mar 26, 2024
e028a8f
update per code review
Two-Hearts Mar 27, 2024
05b8f9c
update per code review
Two-Hearts Mar 27, 2024
449d2aa
update
Two-Hearts Mar 27, 2024
9d2a35b
updated dependency
Two-Hearts Mar 27, 2024
32657ee
update
Two-Hearts Apr 8, 2024
6d13b7d
added support of signing certificate v1
Two-Hearts Apr 10, 2024
94c3b3d
Merge branch 'notaryproject:main' into timestamp
Two-Hearts Apr 10, 2024
284b4d9
update
Two-Hearts Apr 15, 2024
3a4449f
update
Two-Hearts Apr 15, 2024
f83bc02
update
Two-Hearts Apr 15, 2024
366a2cb
update
Two-Hearts Apr 26, 2024
ec1725d
update
Two-Hearts May 8, 2024
f9bddb4
update
Two-Hearts May 10, 2024
e58c4f3
fixed test
Two-Hearts May 10, 2024
5d3b324
update err msg
Two-Hearts May 11, 2024
2944fe3
update err msg
Two-Hearts May 11, 2024
242efab
updated per code review
Two-Hearts May 17, 2024
776293c
fix tests
Two-Hearts May 17, 2024
6a2a0ab
fix tests
Two-Hearts May 17, 2024
a7eb96e
update per code review
Two-Hearts Jun 4, 2024
e5d82db
updated comments
Two-Hearts Jun 4, 2024
5aa2148
resolved conflicts
Two-Hearts Jun 14, 2024
7c5c914
update
Two-Hearts Jun 14, 2024
bd7e551
updated per code review
Two-Hearts Jun 17, 2024
e224399
updated per code review
Two-Hearts Jun 17, 2024
6953545
updated per code review
Two-Hearts Jun 17, 2024
cd78afa
updated per code review
Two-Hearts Jun 18, 2024
8938258
updated per code review
Two-Hearts Jun 18, 2024
c9a7560
root cert pool
Two-Hearts Jun 21, 2024
2126d69
root cert pool
Two-Hearts Jun 21, 2024
df61b1a
update tsa root cert pool
Two-Hearts Jun 21, 2024
09fe8fb
fix
Two-Hearts Jun 21, 2024
22fd76e
fix
Two-Hearts Jun 21, 2024
1284fbf
updated root cert pool
Two-Hearts Jun 24, 2024
b86a837
clean up
Two-Hearts Jun 25, 2024
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
568 changes: 568 additions & 0 deletions conformance_test.go

Large diffs are not rendered by default.

110 changes: 110 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright The Notary Project 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 tspclient

// CertificateNotFoundError is used when identified certificate is not found
// in the timestampe token
type CertificateNotFoundError error

// MalformedRequestError is used when timestamping request is malformed.
type MalformedRequestError struct {
Msg string
Detail error
}

// Error returns error message.
func (e *MalformedRequestError) Error() string {
msg := "malformed timestamping request"
if e.Msg != "" {
msg += ": " + e.Msg
}
if e.Detail != nil {
msg += ": " + e.Detail.Error()
}
return msg
}

// Unwrap returns the internal error.
func (e *MalformedRequestError) Unwrap() error {
return e.Detail
}

// InvalidResponseError is used when timestamping response is invalid.
type InvalidResponseError struct {
Msg string
Detail error
}

// Error returns error message.
func (e *InvalidResponseError) Error() string {
msg := "invalid timestamping response"
if e.Msg != "" {
msg += ": " + e.Msg
}
if e.Detail != nil {
msg += ": " + e.Detail.Error()
}
return msg
}

// Unwrap returns the internal error.
func (e *InvalidResponseError) Unwrap() error {
return e.Detail
}

// SignedTokenVerificationError is used when fail to verify signed token.
type SignedTokenVerificationError struct {
Msg string
Detail error
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
}

// Error returns error message.
func (e *SignedTokenVerificationError) Error() string {
msg := "failed to verify signed token"
if e.Msg != "" {
msg += ": " + e.Msg
}
if e.Detail != nil {
msg += ": " + e.Detail.Error()
}
return msg
}

// Unwrap returns the internal error.
func (e *SignedTokenVerificationError) Unwrap() error {
return e.Detail
}

// TSTInfoError is used when fail a TSTInfo is invalid.
type TSTInfoError struct {
Msg string
Detail error
}

// Error returns error message.
func (e *TSTInfoError) Error() string {
msg := "invalid TSTInfo"
if e.Msg != "" {
msg += ": " + e.Msg
}
if e.Detail != nil {
msg += ": " + e.Detail.Error()
}
return msg
}

// Unwrap returns the internal error.
func (e *TSTInfoError) Unwrap() error {
return e.Detail
}
105 changes: 105 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright The Notary Project 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 tspclient

import (
"errors"
"testing"
)

var errTestInner = errors.New("test inner error")

func TestMalformedRequestError(t *testing.T) {
newErr := MalformedRequestError{}
expectedErrMsg := "malformed timestamping request"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}

newErr = MalformedRequestError{
Detail: errTestInner,
}
expectedErrMsg = "malformed timestamping request: test inner error"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}
innerErr := newErr.Unwrap()
expectedErrMsg = "test inner error"
if innerErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr)
}
}

func TestInvalidResponseError(t *testing.T) {
newErr := InvalidResponseError{}
expectedErrMsg := "invalid timestamping response"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}

newErr = InvalidResponseError{
Detail: errTestInner,
}
expectedErrMsg = "invalid timestamping response: test inner error"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}
innerErr := newErr.Unwrap()
expectedErrMsg = "test inner error"
if innerErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr)
}
}

func TestSignedTokenVerificationError(t *testing.T) {
newErr := SignedTokenVerificationError{Msg: "test error msg"}
expectedErrMsg := "failed to verify signed token: test error msg"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}

newErr = SignedTokenVerificationError{
Detail: errTestInner,
}
expectedErrMsg = "failed to verify signed token: test inner error"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}
innerErr := newErr.Unwrap()
expectedErrMsg = "test inner error"
if innerErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}
}

func TestTSTInfoError(t *testing.T) {
newErr := TSTInfoError{}
expectedErrMsg := "invalid TSTInfo"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}

newErr = TSTInfoError{
Detail: errTestInner,
}
expectedErrMsg = "invalid TSTInfo: test inner error"
if newErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, newErr)
}
innerErr := newErr.Unwrap()
expectedErrMsg = "test inner error"
if innerErr.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, innerErr)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/notaryproject/tspclient-go

go 1.20
go 1.21
121 changes: 121 additions & 0 deletions http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright The Notary Project 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 tspclient

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"time"
)

// maxBodyLength specifies the max content can be received from the remote
// server.
// The legnth of a regular TSA response with certificates is usually less than
// 10 KiB.
var maxBodyLength = 1 * 1024 * 1024 // 1 MiB

// const for MediaTypes defined in RFC 3161 3.4
const (
// MediaTypeTimestampQuery is the content-type of timestamp query.
// RFC 3161 3.4
MediaTypeTimestampQuery = "application/timestamp-query"

// MediaTypeTimestampReply is the content-type of timestamp reply
// RFC 3161 3.4
MediaTypeTimestampReply = "application/timestamp-reply"
)

// httpTimestamper is a HTTP-based timestamper.
type httpTimestamper struct {
httpClient *http.Client
endpoint string
}

// NewHTTPTimestamper creates a HTTP-based timestamper with the endpoint
// provided by the TSA.
// http.DefaultTransport is used if nil RoundTripper is passed.
func NewHTTPTimestamper(httpClient *http.Client, endpoint string) (Timestamper, error) {
if httpClient == nil {
httpClient = &http.Client{Timeout: 5 * time.Second}
}
if _, err := url.Parse(endpoint); err != nil {
return nil, err
}
return &httpTimestamper{
httpClient: httpClient,
endpoint: endpoint,
}, nil
}

// Timestamp sends the request to the remote TSA server for timestamping.
//
// Reference: RFC 3161 3.4 Time-Stamp Protocol via HTTP
func (ts *httpTimestamper) Timestamp(ctx context.Context, req *Request) (*Response, error) {
// sanity check
if err := req.Validate(); err != nil {
return nil, err
}

// prepare for http request
reqBytes, err := req.MarshalBinary()
if err != nil {
return nil, err

Check warning on line 77 in http.go

View check run for this annotation

Codecov / codecov/patch

http.go#L77

Added line #L77 was not covered by tests
}
hReq, err := http.NewRequestWithContext(ctx, http.MethodPost, ts.endpoint, bytes.NewReader(reqBytes))
if err != nil {
return nil, err
}
hReq.Header.Set("Content-Type", MediaTypeTimestampQuery)

// send the request to the remote TSA server
hResp, err := ts.httpClient.Do(hReq)
if err != nil {
return nil, err

Check warning on line 88 in http.go

View check run for this annotation

Codecov / codecov/patch

http.go#L88

Added line #L88 was not covered by tests
}
defer hResp.Body.Close()

// verify HTTP response
if hResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s %q: https response bad status: %s", http.MethodPost, ts.endpoint, hResp.Status)
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
}
if contentType := hResp.Header.Get("Content-Type"); contentType != MediaTypeTimestampReply {
return nil, fmt.Errorf("%s %q: unexpected response content type: %s", http.MethodPost, ts.endpoint, contentType)
}

// read TSA response
lr := &io.LimitedReader{
R: hResp.Body,
N: int64(maxBodyLength),
}
respBytes, err := io.ReadAll(lr)
if err != nil {
return nil, err

Check warning on line 107 in http.go

View check run for this annotation

Codecov / codecov/patch

http.go#L107

Added line #L107 was not covered by tests
}
if lr.N == 0 {
return nil, fmt.Errorf("%s %q: unexpected large http response, max response body size allowed is %d MiB", hResp.Request.Method, hResp.Request.URL, maxBodyLength/1024/1024)
}
var resp Response
if err := resp.UnmarshalBinary(respBytes); err != nil {
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
return nil, err
}
// validate response against RFC 3161
if err := resp.Validate(req); err != nil {
return nil, err
}
return &resp, nil
}
Loading
Loading