go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/encryptedcookies/internal/session_test.go (about)

     1  // Copyright 2021 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package internal
    16  
    17  import (
    18  	"net/http"
    19  	"testing"
    20  
    21  	"github.com/google/tink/go/aead"
    22  	"github.com/google/tink/go/keyset"
    23  
    24  	"go.chromium.org/luci/server/encryptedcookies/session"
    25  	"go.chromium.org/luci/server/encryptedcookies/session/sessionpb"
    26  
    27  	. "github.com/smartystreets/goconvey/convey"
    28  )
    29  
    30  func TestSession(t *testing.T) {
    31  	t.Parallel()
    32  
    33  	Convey("Works", t, func() {
    34  		kh, err := keyset.NewHandle(aead.AES256GCMKeyTemplate())
    35  		So(err, ShouldBeNil)
    36  		primaryAEAD, err := aead.New(kh)
    37  		So(err, ShouldBeNil)
    38  
    39  		cookie, sessionAEAD := NewSessionCookie(session.GenerateID())
    40  		httpCookie, err := EncryptSessionCookie(primaryAEAD, cookie)
    41  		So(err, ShouldBeNil)
    42  
    43  		enc, err := EncryptPrivate(sessionAEAD, &sessionpb.Private{RefreshToken: "blah"})
    44  		So(err, ShouldBeNil)
    45  
    46  		req, _ := http.NewRequest("GET", "http://example.com", nil)
    47  		req.Header.Add("Cookie", httpCookie.String())
    48  
    49  		httpCookieFromReq, _ := req.Cookie(SessionCookieName)
    50  		So(httpCookieFromReq, ShouldNotBeNil)
    51  
    52  		cookieFromReq, err := DecryptSessionCookie(primaryAEAD, httpCookieFromReq)
    53  		So(err, ShouldBeNil)
    54  
    55  		priv, _, err := UnsealPrivate(cookieFromReq, &sessionpb.Session{
    56  			EncryptedPrivate: enc,
    57  		})
    58  		So(err, ShouldBeNil)
    59  
    60  		So(priv.RefreshToken, ShouldEqual, "blah")
    61  	})
    62  }