@@ -17,8 +17,12 @@ limitations under the License.
1717package controllers
1818
1919import (
20+ "bytes"
2021 "context"
22+ "crypto/sha1"
23+ "crypto/sha256"
2124 "fmt"
25+ "io"
2226 "io/ioutil"
2327 "net/http"
2428 "os"
@@ -119,11 +123,40 @@ func (r *GitRepositoryWatcher) fetchArtifact(ctx context.Context, repository sou
119123 return "" , fmt .Errorf ("failed to download artifact, status: %s" , resp .Status )
120124 }
121125
126+ var buf bytes.Buffer
127+
128+ // verify checksum matches origin
129+ if err := r .verifyArtifact (repository .GetArtifact (), & buf , resp .Body ); err != nil {
130+ return "" , err
131+ }
132+
122133 // extract
123- summary , err := untar .Untar (resp . Body , dir )
134+ summary , err := untar .Untar (& buf , dir )
124135 if err != nil {
125136 return "" , fmt .Errorf ("faild to untar artifact, error: %w" , err )
126137 }
127138
128139 return summary , nil
129140}
141+
142+ func (r * GitRepositoryWatcher ) verifyArtifact (artifact * sourcev1.Artifact , buf * bytes.Buffer , reader io.Reader ) error {
143+ hasher := sha256 .New ()
144+
145+ // for backwards compatibility with source-controller v0.17.2 and older
146+ if len (artifact .Checksum ) == 40 {
147+ hasher = sha1 .New ()
148+ }
149+
150+ // compute checksum
151+ mw := io .MultiWriter (hasher , buf )
152+ if _ , err := io .Copy (mw , reader ); err != nil {
153+ return err
154+ }
155+
156+ if checksum := fmt .Sprintf ("%x" , hasher .Sum (nil )); checksum != artifact .Checksum {
157+ return fmt .Errorf ("failed to verify artifact: computed checksum '%s' doesn't match advertised '%s'" ,
158+ checksum , artifact .Checksum )
159+ }
160+
161+ return nil
162+ }
0 commit comments