-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
609c08a
commit 367c587
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package mdm | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"crypto/x509" | ||
"errors" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/micromdm/nanomdm/log" | ||
) | ||
|
||
const ( | ||
testHash = "ZZZYYYXXX" | ||
testID = "AAABBBCCC" | ||
) | ||
|
||
func testHashCert(_ *x509.Certificate) string { | ||
return testHash | ||
} | ||
|
||
type testCertAuthRetriever struct{} | ||
|
||
func (c *testCertAuthRetriever) EnrollmentFromHash(ctx context.Context, hash string) (string, error) { | ||
if hash != testHash { | ||
return "", errors.New("invalid test hash") | ||
} | ||
return testID, nil | ||
} | ||
|
||
func TestCertWithEnrollmentIDMiddleware(t *testing.T) { | ||
response := []byte("mock response") | ||
|
||
// mock handler | ||
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
w.WriteHeader(http.StatusOK) | ||
w.Write(response) | ||
}) | ||
|
||
handler = CertWithEnrollmentIDMiddleware(handler, testHashCert, &testCertAuthRetriever{}, true, log.NopLogger) | ||
|
||
req, err := http.NewRequest("GET", "/test", nil) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
rr := httptest.NewRecorder() | ||
handler.ServeHTTP(rr, req) | ||
|
||
// we requested enforcement, so make sure we get a BadResponse | ||
if have, want := rr.Code, http.StatusBadRequest; have != want { | ||
t.Errorf("have: %d, want: %d", have, want) | ||
} | ||
|
||
req, err = http.NewRequest("GET", "/test", nil) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
req = req.WithContext(context.WithValue(req.Context(), contextKeyCert{}, &x509.Certificate{})) | ||
|
||
rr = httptest.NewRecorder() | ||
handler.ServeHTTP(rr, req) | ||
|
||
// now that we have a "cert" included, we should get an OK | ||
if have, want := rr.Code, http.StatusOK; have != want { | ||
t.Errorf("have: %d, want: %d", have, want) | ||
} | ||
|
||
// verify the actual body, too | ||
if !bytes.Equal(rr.Body.Bytes(), response) { | ||
t.Error("body not equal") | ||
} | ||
} |