~bigbes/sr-ht-ecore

ref: 43ad9287cc063fc6a74e1398a3a8b642631cbcae sr-ht-ecore/bearer/status_test.go -rw-r--r-- 2.1 KiB
43ad9287 — Eugene Blikh bearer: say what IsRefusal does not answer for 9 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package bearer

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestStatusForKeepsTheUnreachableDaemonOutOfThe401(t *testing.T) {
	// The arm the whole table exists for: a token service that cannot be
	// reached must not read as a bad credential.
	assert.Equal(t, http.StatusServiceUnavailable, StatusFor(ErrUnavailable))
	assert.Equal(t, http.StatusServiceUnavailable,
		StatusFor(fmt.Errorf("ask tokens.sr.ht: %w", ErrUnavailable)),
		"a wrapped one too — services wrap before returning")

	assert.Equal(t, http.StatusForbidden, StatusFor(ErrForbidden))
	assert.Equal(t, http.StatusForbidden,
		StatusFor(fmt.Errorf("check the grant: %w", ErrForbidden)))

	// The three the caller is responsible for answer alike, on purpose.
	for _, err := range []error{ErrInvalid, ErrRevoked, ErrNotOurs} {
		assert.Equal(t, http.StatusUnauthorized, StatusFor(err), "%v", err)
	}

	assert.Equal(t, http.StatusOK, StatusFor(nil))
	assert.Equal(t, http.StatusUnauthorized, StatusFor(errors.New("something new")),
		"an unrecognised failure refuses the request rather than declaring the service unwell")
}

// TestIsRefusalSeparatesOurVocabularyFromTheServices is the guard a resolver
// needs: its own failures must not be answered as a bad credential.
func TestIsRefusalSeparatesOurVocabularyFromTheServices(t *testing.T) {
	for _, err := range []error{ErrInvalid, ErrNotOurs, ErrForbidden, ErrRevoked, ErrUnavailable} {
		assert.True(t, IsRefusal(err), "%v", err)
		assert.True(t, IsRefusal(fmt.Errorf("validate the token: %w", err)), "wrapped %v", err)
	}

	assert.False(t, IsRefusal(nil))
	assert.False(t, IsRefusal(errors.New("dial tcp 127.0.0.1:5432: connection refused")),
		"a database that did not answer is not a refused credential")
	assert.False(t, IsRefusal(context.DeadlineExceeded))
}

func TestChallengeNamesTheServiceAndQuotesIt(t *testing.T) {
	assert.Equal(t, `Bearer realm="bench.sr.ht"`, Challenge("bench.sr.ht"))
	assert.Equal(t, `Bearer realm="dolt.sr.ht"`, Challenge("dolt.sr.ht"))
	// A quote in the realm would end the parameter early if it were pasted in.
	assert.Equal(t, `Bearer realm="a\"b"`, Challenge(`a"b`))
}